'use client'

import { useState, useRef } from 'react'
import Image from 'next/image'
import searchIcon from '@/public/search_black.png'
import xmarkIcon from '@/public/xmark_gray_fill.png'
import { useRouter } from '@/src/navigation'

interface SearchProps {
  placeholder: string
  onClose: () => void
}

const Search: React.FC<SearchProps> = (props) => {
  const { placeholder, onClose } = props
  const dropDownRef = useRef(null)
  const [searchText, setSearchText] = useState('')
  const router = useRouter()

  const handleKeyUp = (e: any) => {
    if (e.key === 'Enter') {
      onClose()
      router.push(`/searchResult?keyword=${searchText}`)
    }
  }

  return (
    <div
      ref={dropDownRef}
      className='fixed top-0 left-0 w-screen h-[14.09375rem] lg:h-[8.3125rem] 2xl:h-[12.46875rem] p-[0.9375rem] bg-white'
      onClick={(e) => e.stopPropagation()}
    >
      <div className='flex items-center rounded-[0.3125rem] space-x-2 lg:mt-12 2xl:mt-[4.5rem] max-w-[20.8125rem] 2xl:max-w-[31.21875rem] mx-auto bg-[#f8f8f8] lg:bg-transparent lg:border-b-[1px] lg:border-b-solid lg:border-b-[#EBEBEB] px-[0.9375rem] 2xl:px-[1.40625rem] 2xl:space-x-3'>
        <div className='relative flex-shrink-0 w-[0.8125rem] h-[0.8125rem] 2xl:w-[1.21875rem] 2xl:h-[1.21875rem]'>
          <Image
            src={searchIcon}
            alt='search icon'
            fill
            sizes='(max-width: 1024px) 5vw'
          />
        </div>
        <input
          value={searchText}
          type='text'
          className='flex-1 h-[2.75rem] bg-transparent outline-none 2xl:h-[4.125rem]'
          placeholder={placeholder}
          autoFocus
          onInput={(e) => setSearchText((e.target as any).value)}
          onKeyUp={handleKeyUp}
        />
        <div
          className='relative flex-shrink-0 w-[0.71875rem] h-[0.71875rem] 2xl:w-[1.078125rem] 2xl:h-[1.078125rem]'
          onClick={() => setSearchText('')}
        >
          <Image
            src={xmarkIcon}
            alt='search icon'
            fill
            sizes='(max-width: 1024px) 5vw'
          />
        </div>
      </div>
    </div>
  )
}

export default Search
